var app = angular.module('BaseServer');

app.service('PublicModule', ['PublicService', 'PublicFunction', 'PublicEnum',
    function(PublicService, PublicFunction, PublicEnum) {
        var publicModule = function (scope, entityName, queryParameter) {
            this.ParentModule = null;
            this.ChildModules = new Array();

            this.EntityName = entityName;
            this._ID;
            this.IsEntityModule = true;
            this._scope = scope;
            this._Records = new Array();
            this._DeleteRecords = new Array();

            this.__defineGetter__('Records', function(){
                return this._Records;
            });
            this.__defineSetter__('Records', function(val){
                this._Records = val;
                if(val == null){
                    this._Records = new Array();
                }
                if(val.length == 0)
                {
                    this.FocusedRecord = null;
                    if(this.LoadMode == PublicEnum.LoadMode.CacheAndNoPaging || this.LoadMode == PublicEnum.LoadMode.CacheAndDelay){
                        this.RecordCount = 0;
                    }
                }
            });

            this.FocusedRecord = null;
            this._newRecordID = -1;

            this.QueryParameter = {
                FixedCondition: null,
                Condition: null,
                OrderBy: null,
                Populate: ''
            };
            this._PageParameter = {
                RecordCount: 0,
                PageSize: 1,
                PageNum: 0,
                PageCount: 0
            };

            this.Pages = {
                FocusedPageIndex: -1,
                RecordPages: new Array()
            };

            //数据加载模式
            this.LoadMode = PublicEnum.LoadMode.NoCacheAndPaging;
            //当LoadMode == 2的时候必须设置延迟模式
            this.DelayMode = {
                DelayTime: 0            //延长多少毫秒后加载
                //OnceLoadDataCount: -1   //一次加载多少条，-1为一次加载剩下的全部
            };

            this.__defineGetter__('RecordCount', function(){
                return this._PageParameter.RecordCount;
            });
            this.__defineSetter__('RecordCount', function(val){
                if(this.RecordCount !== val){
                    this._PageParameter.RecordCount = val;
                    this.PageCount = Math.ceil(this.RecordCount / this.PageSize);
                }
            });
            this.__defineGetter__('PageNum', function(){
                return this._PageParameter.PageNum;
            });
            this.__defineSetter__('PageNum', function(val){
                if(this.PageNum !== val){
                    this._PageParameter.PageNum = val;
                    this.refreshDataGrid();
                    this._scope.$broadcast("PageToolbar" + this._ID);
                }
            });
            this.__defineGetter__('PageCount', function(){
                return this._PageParameter.PageCount;
            });
            this.__defineSetter__('PageCount', function(val){
                if(this.PageCount !== val){
                    this._PageParameter.PageCount = val;
                    if(val == 0){
                        this._PageParameter.PageNum = 0;
                    }
                    this._scope.$broadcast("PageToolbar" + this._ID);
                }
            });
            this.__defineGetter__('PageSize', function(){
                return this._PageParameter.PageSize;
            });
            this.__defineSetter__('PageSize', function(val){
                if(this.PageSize !== val){
                    this._PageParameter.PageSize = val;
                    this.PageCount = Math.ceil(this.RecordCount / this.PageSize);
                }
            });

            if(entityName.substring(0, 1) == "_"){
                this.IsEntityModule = false;
                this.PageSize = 10;
                this.LoadMode = PublicEnum.LoadMode.CacheAndNoPaging;
            }

            if(queryParameter != undefined && queryParameter != null){
                this.QueryParameter = queryParameter;
            }
            this.QueryParameter.FixedCondition = this.QueryParameter.Condition;

            if((this.LoadMode == PublicEnum.LoadMode.NoCacheAndPaging || 
                this.LoadMode == PublicEnum.LoadMode.CacheAndPaging) && this.IsEntityModule){
                var self = this;
                this.queryRecordCount(function(recordCount) {
                    self.RecordCount = recordCount;
                });
            }
        };

        publicModule.prototype = {
            //从数据库提取数据方法
            load: function(condition, orderBy, completeFun){
                if(this.IsEntityModule){
                    this.Records = new Array();
                    this._DeleteRecords = new Array();
                    this._PageParameter.RecordCount = 0;
                    this._PageParameter.PageNum = 0;
                    this._PageParameter.PageCount = 0;

                    if(condition == undefined || condition == null){
                        condition = this.QueryParameter.Condition;
                    }
                    if(orderBy == undefined || orderBy == null){
                        orderBy = this.QueryParameter.OrderBy;
                    }

                    if(this.ParentModule != null){
                        if(this.ParentModule.FocusedRecord == null || this.ParentModule.FocusedRecord.RowStatus == PublicEnum.RowStatus.Insert){
                            this.clearRecords();
                            if (completeFun != undefined && completeFun != null) {
                                completeFun(records);
                            }
                            return;
                        }
                        else{
                            if(condition == null){
                                condition = eval("({" + this.ParentModule.EntityName + ": '" + this.ParentModule.FocusedRecord._id + "'})");
                            }
                            else{
                                eval("condition." + this.ParentModule.EntityName + " = '" + this.ParentModule.FocusedRecord._id + "'");
                            }
                        }
                    }

                    var self = this;
                    this.Records = new Array();
                    if(this.LoadMode == PublicEnum.LoadMode.CacheAndNoPaging){
                        this.loadAll(condition, orderBy,
                            function(){
                                self.RecordCount = self.Records.length;
                                self.firstPage();

                                if(completeFun != undefined && completeFun != null) {
                                    completeFun(self.Records);
                                }
                            }
                        );
                    }
                    else if(this.LoadMode == PublicEnum.LoadMode.CacheAndPaging){
                        self.queryRecordCount(function(count){
                            self.RecordCount = count;
                            self.Pages.RecordPages = new Array(self.PageCount);

                            if(count > 0) {
                                self.loadByPage(condition, orderBy, 0,
                                    function (records) {
                                        self.Pages.RecordPages[0] = records;
                                        self.firstPage();

                                        if (completeFun != undefined && completeFun != null) {
                                            completeFun(records);
                                        }
                                    }
                                );
                            }
                            else{
                                self.clearRecords();
                                if (completeFun != undefined && completeFun != null) {
                                    completeFun();
                                }
                            }
                        });
                    }
                    else if(this.LoadMode == PublicEnum.LoadMode.CacheAndDelay){
                        PublicFunction.loading(false);
                        this.loadByPage(condition, orderBy, 0,
                            function(records){
                                self.RecordCount = records.length;
                                self.firstPage();

                                PublicFunction.loading(true);
                                self.queryRecordCount(function(count){
                                    var recordCount = count;
                                    var pageCount = Math.ceil(recordCount / self.PageSize);
                                    if (pageCount > 1) {
                                        var pageIndex = 1;
                                        var delayLoading = function(pageIndex){
                                            self.loadByPage(null, null, pageIndex, function (records) {
                                                self.RecordCount = self.Records.length;

                                                // if(self.Records.length > 0){
                                                //     self.FocusedRecord = self.Records[0];
                                                // }
                                                if (pageIndex == pageCount - 1) {
                                                    if (completeFun != undefined && completeFun != null) {
                                                        completeFun(records);
                                                    }
                                                } else {
                                                    pageIndex++;
                                                    window.setTimeout(function(){delayLoading(pageIndex)}, self.DelayMode.DelayTime);
                                                }
                                            });
                                        };
                                        window.setTimeout(function(){delayLoading(1)}, self.DelayMode.DelayTime);
                                    }
                                });
                            }
                        );
                    }
                    else if(this.LoadMode == PublicEnum.LoadMode.NoCacheAndPaging) {
                        this.loadByPage(condition, orderBy, 0,
                            function(records){
                                self.queryRecordCount(function(count){
                                    self.RecordCount = count;
                                    self.firstPage();

                                    if(completeFun != undefined && completeFun != null) {
                                        completeFun(records);
                                    }
                                }
                            );
                        });
                    }
                }
            },
            loadAll: function(condition, orderBy, completeFun){
                if(this.IsEntityModule){
                    if(condition == undefined || condition == null){
                        condition = this.QueryParameter.Condition;
                    }
                    if(orderBy == undefined || orderBy == null){
                        orderBy = this.QueryParameter.OrderBy;
                    }

                    if(this.ParentModule != null){
                        if(this.ParentModule.FocusedRecord == null || this.ParentModule.FocusedRecord.RowStatus == PublicEnum.RowStatus.Insert){
                            this.clearRecords();
                            if (completeFun != undefined && completeFun != null) {
                                completeFun(records);
                            }
                            return;
                        }
                        else{
                            if(condition == null){
                                condition = eval("({" + this.ParentModule.EntityName + ": '" + this.ParentModule.FocusedRecord._id + "'})");
                            }
                            else{
                                eval("condition." + this.ParentModule.EntityName + " = '" + this.ParentModule.FocusedRecord._id + "'");
                            }
                        }
                    }

                    this.Records = new Array();
                    var self = this;

                    PublicFunction.loading(true);
                    PublicService.find(this.EntityName, condition, orderBy, this.QueryParameter.Populate,
                        function (res) {
                            self.Records = res.Data;
                            if (self.Records.length > 0) {
                                for (var i = 0; i < self.Records.length; i++) {
                                    self.Records[i].RowStatus = PublicEnum.RowStatus.UnChange;
                                    self.Records[i].IsSelected = false;
                                }
                            }
                            PublicFunction.loading(false);
                            if(completeFun != undefined && completeFun != null) {
                                completeFun();
                            }
                        }
                    );
                }
            },
            loadByPage: function(condition, orderBy, pageNum, completeFun){
                if(this.IsEntityModule){
                    if(condition == undefined || condition == null){
                        condition = this.QueryParameter.Condition;
                    }
                    if(orderBy == undefined || orderBy == null){
                        orderBy = this.QueryParameter.OrderBy;
                    }
                    if(pageNum == undefined || pageNum == null){
                        pageNum = this.PageNum;
                    }

                    if(this.ParentModule != null){
                        if(this.ParentModule.FocusedRecord == null || this.ParentModule.FocusedRecord.RowStatus == PublicEnum.RowStatus.Insert){
                            this.clearRecords();
                            if (completeFun != undefined && completeFun != null) {
                                completeFun(records);
                            }
                            return;
                        }
                        else{
                            if(condition == null){
                                condition = eval("({" + this.ParentModule.EntityName + ": '" + this.ParentModule.FocusedRecord._id + "'})");
                            }
                            else{
                                eval("condition." + this.ParentModule.EntityName + " = '" + this.ParentModule.FocusedRecord._id + "'");
                            }
                        }
                    }

                    if(this.LoadMode != PublicEnum.LoadMode.CacheAndDelay){
                        PublicFunction.loading(true);
                    }
                    var self = this;
                    PublicService.pageQuery(self.EntityName, condition, orderBy, self.QueryParameter.Populate,
                        pageNum, this.PageSize,
                        function(res){
                            var returnRecords = res.Data;
                            for(var i=0; i<returnRecords.length; i++){
                                returnRecords[i].RowStatus = PublicEnum.RowStatus.UnChange;
                                returnRecords[i].IsSelected = false;
                                self.Records.push(returnRecords[i]);
                            }

                            if(self.LoadMode != PublicEnum.LoadMode.CacheAndDelay){
                                PublicFunction.loading(false);
                            }
                            if(completeFun != undefined && completeFun != null) {
                                completeFun(returnRecords);
                            }
                        }
                    );
                }
            },
            findById: function(id, completeFun){
                if(this.IsEntityModule){
                    PublicService.find(this.EntityName, {_id: id}, null, this.QueryParameter.Populate,
                        function (res) {
                            if(completeFun != undefined && completeFun != null && res.Data.length > 0) {
                                res.Data[0].RowStatus = PublicEnum.RowStatus.UnChange;
                                res.Data[0].IsSelected = false;
                                completeFun(res.Data[0]);
                            }
                            else{
                                completeFun(null);
                            }
                        }
                    );
                }
            },
            find: function(condition, orderBy, completeFun){
                if(this.IsEntityModule){
                    PublicService.find(this.EntityName, condition, orderBy, this.QueryParameter.Populate,
                        function (res) {
                            var records = res.Data;
                            if (records.length > 0) {
                                for (var i = 0; i < records.length; i++) {
                                    records[i].RowStatus = PublicEnum.RowStatus.UnChange;
                                    records[i].IsSelected = false;
                                }
                            }
                            if(completeFun != undefined && completeFun != null) {
                                completeFun(records);
                            }
                        }
                    );
                }
            },
            findRecordIndex: function(completeFun){
                if(this.IsEntityModule){
                    PublicService.findRecordIndex(this.EntityName,
                        this.FocusedRecord._id,
                        { CreatedOn : {$lte : new Date(2015, 7, 27, 0, 0, 0)} } ,
                        { CreatedOn: -1 },
                        function(res){
                            if(completeFun != undefined && completeFun != null) {
                                completeFun(res.Data);
                            }
                        }
                    );
                }
            },
            queryRecordCount: function(completeFun){
                if(this.IsEntityModule){
                    var condition = this.QueryParameter.Condition;
                    if(this.ParentModule != null){
                        if(this.ParentModule.FocusedRecord == null || this.ParentModule.FocusedRecord.RowStatus == PublicEnum.RowStatus.Insert){
                            this.clearRecords();
                            if (completeFun != undefined && completeFun != null) {
                                completeFun(records);
                            }
                            return;
                        }
                        else{
                            if(condition == null){
                                condition = eval("({" + this.ParentModule.EntityName + ": '" + this.ParentModule.FocusedRecord._id + "'})");
                            }
                            else{
                                eval("condition." + this.ParentModule.EntityName + " = '" + this.ParentModule.FocusedRecord._id + "'");
                            }
                        }
                    }

                    var self = this;
                    PublicService.queryRecordCount(this.EntityName, condition,
                        function(res){
                            if(completeFun != undefined && completeFun != null) {
                                completeFun(res.Data);
                            }
                        }
                    );
                }
            },
            search: function(text, limit, completeFun){
                if(text.trim() == ""){
                    return;
                }
                if(limit == undefined){
                    limit = null;
                }
                PublicService.search(this.EntityName, text, this.Condition, limit, function(records){
                    completeFun(records.Data);
                });
            },

            //20160225模糊查询
            queryByKeyword:function(condition, orderBy, completeFun){
                if(this.IsEntityModule){
                    PublicService.queryByKeyword(this.EntityName, condition, orderBy, this.QueryParameter.Populate,
                        function (res) {
                            var records = res.Data;
                            if (records.length > 0) {
                                for (var i = 0; i < records.length; i++) {
                                    records[i].RowStatus = PublicEnum.RowStatus.UnChange;
                                    records[i].IsSelected = false;
                                }
                            }
                            if(completeFun != undefined && completeFun != null) {
                                completeFun(records);
                            }
                        }
                    );
                }
            },

            //持久化方法
            _setDefaultValue: function(record){
                if(this.QueryParameter.Populate !== ''){
                    if(this.QueryParameter.Populate.constructor === Object){
                        if(record[this.QueryParameter.Populate.path] != undefined && record[this.QueryParameter.Populate.path] != null && record[this.QueryParameter.Populate.path] != ""){
                            if(record[this.QueryParameter.Populate.path]._id !== null && 
                                record[this.QueryParameter.Populate.path]._id != undefined &&
                                record[this.QueryParameter.Populate.path]._id !== ""){
                                record[this.QueryParameter.Populate.path] = record[this.QueryParameter.Populate.path]._id;
                            }
                            else{
                                record[this.QueryParameter.Populate.path] = null;
                            }
                        }
                    }
                    else if(this.QueryParameter.Populate.constructor === Array){
                        for(var i=0; i<this.QueryParameter.Populate.length; i++){
                            if(record[this.QueryParameter.Populate[i].path] != undefined && record[this.QueryParameter.Populate[i].path] != null && 
                                record[this.QueryParameter.Populate[i].path] != ""){
                                if(record[this.QueryParameter.Populate[i].path]._id !== null && 
                                record[this.QueryParameter.Populate[i].path]._id != undefined &&
                                record[this.QueryParameter.Populate[i].path]._id !== ""){
                                    record[this.QueryParameter.Populate[i].path] = record[this.QueryParameter.Populate[i].path]._id;
                                }
                                else{
                                    record[this.QueryParameter.Populate[i].path] = null;
                                }
                            }
                        }
                    }
                    else if(this.QueryParameter.Populate.constructor === String){
                        var strPopulates = this.QueryParameter.Populate.trim().replace(/  /g, " ").split(" ");
                        for(var i=0; i<strPopulates.length; i++){
                            if(record[strPopulates[i]] != undefined && record[strPopulates[i]] != null && record[strPopulates[i]] != ""){
                                if(record[strPopulates[i]]._id !== null && 
                                record[strPopulates[i]]._id != undefined &&
                                record[strPopulates[i]]._id !== ""){
                                    record[strPopulates[i]] = record[strPopulates[i]]._id;
                                }
                                else{
                                    record[strPopulates[i]] = null;
                                }
                            }
                        }
                    }
                }
            },
            save: function (successFun, errFunction) {
                if(this.IsEntityModule){
                    var self = this;
                    if(this.PageSize == 1) {
                        if(this.FocusedRecord != null && this.FocusedRecord.RowStatus != PublicEnum.RowStatus.UnChange) {
                            var recording = [];     //记录ref的值，因为保存之后不会返回来
                            if(this.QueryParameter.Populate !== ''){
                                if(this.QueryParameter.Populate.constructor === Object){
                                    if(this.FocusedRecord[this.QueryParameter.Populate.path] != undefined && 
                                        this.FocusedRecord[this.QueryParameter.Populate.path] != null && 
                                        this.FocusedRecord[this.QueryParameter.Populate.path] != ""){
                                        var strPath = this.QueryParameter.Populate.path;
                                        recording.push({FieldName : strPath, Value: this.FocusedRecord[strPath]});
                                    }
                                }
                                else if(this.QueryParameter.Populate.constructor === Array){
                                    for(var i=0; i<this.QueryParameter.Populate.length; i++){
                                        if(this.FocusedRecord[this.QueryParameter.Populate[i].path] != undefined && 
                                            this.FocusedRecord[this.QueryParameter.Populate[i].path] != null && 
                                            this.FocusedRecord[this.QueryParameter.Populate[i].path] != ""){
                                            var strPath = this.QueryParameter.Populate[i].path;
                                            recording.push({FieldName : strPath, Value: this.FocusedRecord[strPath]});
                                        }
                                    }
                                }
                                else if(this.QueryParameter.Populate.constructor === String){
                                    var strPopulates = this.QueryParameter.Populate.trim().replace(/  /g, " ").split(" ");
                                    for(var i=0; i<strPopulates.length; i++){
                                        if(this.FocusedRecord[strPopulates[i]] != undefined && 
                                            this.FocusedRecord[strPopulates[i]] != null && 
                                            this.FocusedRecord[strPopulates[i]] != ""){
                                            var strPath = strPopulates[i];
                                            recording.push({FieldName : strPath, Value: this.FocusedRecord[strPath]});
                                        }
                                    }
                                }
                            }

                            this._setDefaultValue(this.FocusedRecord);
                            var isSelected = this.FocusedRecord.IsSelected;
                            PublicService.save(this.EntityName, [this.FocusedRecord], function (res) {
                                PublicFunction.tip("保存完成");
                                res.Data.IsSelected = isSelected;
                                for(var i=0; i<recording.length; i++){
                                    res.Data[recording[i].FieldName] = recording[i].Value;
                                }
                                res.Data.RowStatus = PublicEnum.RowStatus.UnChange;
                                self.Records[0] = res.Data;
                                self.FocusedRecord = self.Records[0];
                                self.queryRecordCount(function(count){
                                    self.RecordCount = count;
                                    if (successFun != undefined) {
                                        successFun();
                                    }
                                });
                            },
                            errFunction);
                        }
                        else{
                            if (successFun != undefined) {
                                successFun();
                            }
                        }
                    }
                    else {
                        var saveRecords = new Array();

                        for(var i=0; i<this.Records.length; i++){
                            if(this.Records[i].RowStatus != PublicEnum.RowStatus.UnChange){
                                this._setDefaultValue(this.Records[i]);
                                saveRecords.push(this.Records[i]);
                            }
                        }
                        saveRecords = saveRecords.concat(this._DeleteRecords);

                        if(saveRecords.length > 0) {
                            PublicService.save(this.EntityName, saveRecords,
                                function (res) {
                                    PublicFunction.tip("操作完成");
                                    self.load(null, null, function(){
                                        if(successFun != undefined){
                                            successFun(res.Data);
                                        }
                                        self.queryRecordCount(function(count){
                                            self.RecordCount = count;
                                            self.firstPage();
                                        });
                                    });
                                }
                            );
                        }
                        else{
                            if (successFun != undefined) {
                                successFun();
                            }
                        }
                    }
                }
            },
            updateByValue: function(condition, value, completeFun){
                if(condition == null || condition == undefined){
                    condition = {_id: this.FocusedRecord._id};
                }
                PublicService.updateByValue(this.EntityName, condition, value, completeFun);
            },
            add: function(recordIndex){
                if(this.PageSize == 1){
                    this.Records = new Array();
                }

                var newRecord = {
                    _id: this._newRecordID--,
                    RowStatus: PublicEnum.RowStatus.Insert,
                    IsSelected: false
                };

                if(this.ParentModule != null){
                    if(this.ParentModule.FocusedRecord != null) {
                        eval('newRecord.' + this.ParentModule.EntityName + ' = "' + this.ParentModule.FocusedRecord._id + '"');
                    }
                }
                if(recordIndex != undefined){
                    this.Records.splice(recordIndex, 0, newRecord);
                }
                else {
                    this.Records.push(newRecord);
                }

                if(this.LoadMode == PublicEnum.LoadMode.CacheAndNoPaging ||
                    this.LoadMode == PublicEnum.LoadMode.CacheAndDelay) {
                    this.RecordCount = this.Records.length;
                }
                else if(this.LoadMode == PublicEnum.LoadMode.CacheAndPaging){
                    if(recordIndex != undefined){
                        for(var i=0; i<this.Pages.RecordPages[this.Pages.FocusedPageIndex].length; i++){
                            if(this.Pages.RecordPages[this.Pages.FocusedPageIndex][i]._id == this.FocusedRecord._id){
                                this.Pages.RecordPages[this.Pages.FocusedPageIndex].splice(i+1, 0, newRecord);
                                break;
                            }
                        }
                    }
                    else {
                        this.Pages.RecordPages[this.Pages.FocusedPageIndex].push(newRecord);
                    }
                    this.RecordCount++;
                }
                else if(this.LoadMode == PublicEnum.LoadMode.NoCacheAndPaging){
                    // this.RecordCount++;
                }
                this.FocusedRecord = newRecord;
                return newRecord;
            },
            delete: function(completeFun){
                if (this.PageSize == 1) {
                    if (this.FocusedRecord.RowStatus == PublicEnum.RowStatus.Insert) {
                        this.Records = [];
                        this.FocusedRecord = null;

                        if(this.LoadMode == PublicEnum.LoadMode.CacheAndNoPaging ||
                            this.LoadMode == PublicEnum.LoadMode.CacheAndDelay) {
                            this.RecordCount = this.Records.length;
                        }
                        else if(this.LoadMode == PublicEnum.LoadMode.NoCacheAndPaging){
                            this.RecordCount--;
                        }

                        if(this.PageCount > 0){
                            this.firstPage(function(){
                                if(completeFun != undefined && completeFun != null) {
                                    completeFun();
                                }
                            });
                        }
                        else{
                            if(completeFun != undefined && completeFun != null) {
                                completeFun();
                            }
                        }
                    }
                    else{
                        if(this.IsEntityModule){
                            var self = this;
                            PublicService.deleteById(this.EntityName, this.FocusedRecord._id,
                                function (res) {
                                     var recordIndex = self.Records.indexOf(self.FocusedRecord);
                                    if (recordIndex > -1) {
                                        self.Records.splice(recordIndex, 1);
                                    }
                                    self.FocusedRecord = null;

                                    if(self.LoadMode == PublicEnum.LoadMode.CacheAndNoPaging ||
                                        self.LoadMode == PublicEnum.LoadMode.CacheAndDelay) {
                                        self.RecordCount--;
                                    }
                                    else if(self.LoadMode == PublicEnum.LoadMode.CacheAndPaging){
                                        self.RecordCount--;
                                    }
                                    else if(self.LoadMode == PublicEnum.LoadMode.NoCacheAndPaging){
                                        self.RecordCount--;
                                    }

                                    PublicFunction.tip("删除完成");

                                    if(self.PageCount > 0){
                                        self.firstPage(function(){
                                            if(completeFun != undefined && completeFun != null) {
                                                completeFun();
                                            }
                                        });
                                    }
                                    else{
                                        if(completeFun != undefined && completeFun != null) {
                                            completeFun();
                                        }
                                    }
                                }
                            );
                        }
                    }
                }
                else {
                    this.deleteRecord(this.FocusedRecord);

                    if(completeFun != undefined && completeFun != null) {
                        completeFun();
                    }
                }
            },
            cancel: function(afterCancel){
                if(this.PageSize == 1) {
                    if(this.FocusedRecord.RowStatus == PublicEnum.RowStatus.Insert){
                        this.Records = [];
                        this.FocusedRecord = this.add();

                        if(afterCancel != undefined){
                            afterCancel();
                        }
                    }
                    else{
                        var self = this;
                        this.findById(this.FocusedRecord._id, function(record){
                            self.FocusedRecord = record;

                            if(afterCancel != undefined){
                                afterCancel();
                            }
                        });
                    }
                }
                else{
                    this.FocusedRecord = null;
                    if(this.EntityName.substring(0,1) == "_"){
                        this.Records = [];
                        if(afterCancel != undefined){
                            afterCancel();
                        }
                    }
                    else{
                        this.Records = [];
                        this.load(null, null, function(){
                            if(afterCancel != undefined){
                                afterCancel();
                            }
                        });
                    }
                }
            },
            //主要争对列表的批量删除并持久化数据库
            deleteSelecteds: function(completeFun){
                if(this.IsEntityModule){
                    var selectRecords = this.getSelectRecords();
                    var ids = [];
                    for(var i=0; i <selectRecords.length; i++){
                        ids.push(selectRecords[i]._id);
                    }

                    var self = this;
                    PublicService.deleteByIds(this.EntityName, ids,
                        function (res) {
                            PublicFunction.tip("批量删除完成");
                            var result = res.Data;
                            self.load(null, null, completeFun);
                        },
                        function(err){
                            PublicFunction.alert(err.data.message, err.data.title);
                            self.load(null, null, completeFun);
                        }
                    );
                }
            },

            //module层的数据操作方法
            deleteRecord: function(record){
                if(this.FocusedRecord != null && this.FocusedRecord._id == record._id){
                    this.FocusedRecord = null;
                }

                var recordIndex = this.Records.indexOf(record);
                if (record.RowStatus == PublicEnum.RowStatus.Insert) {
                    if (recordIndex > -1) {
                        this.Records.splice(recordIndex, 1);
                    }
                }
                else {
                    record.RowStatus = PublicEnum.RowStatus.Delete;
                    this._DeleteRecords.push(this.Records.splice(this.Records.indexOf(record), 1)[0]);
                }

                if(this.LoadMode == PublicEnum.LoadMode.CacheAndNoPaging ||
                    this.LoadMode == PublicEnum.LoadMode.CacheAndDelay) {
                    this.RecordCount = this.Records.length;
                }
                else if(this.LoadMode == PublicEnum.LoadMode.CacheAndPaging){
                    this.Pages.RecordPages[this.Pages.FocusedPageIndex].splice(this.Pages.RecordPages[this.Pages.FocusedPageIndex].indexOf(record), 1)
                    this.RecordCount--;
                }
                else if(this.LoadMode == PublicEnum.LoadMode.NoCacheAndPaging){
                    this.RecordCount--;
                }
            },
            deleteRecords: function(records){
                for(var i=0; i<records.length; i++){
                    this.deleteRecord(records[i]);
                }
            },
            clearRecords: function(){
                this.Records = [];
                this._DeleteRecords = [];
                this.refreshDataGrid();
            },
            getSelectRecords: function(){
                var selectRecords = [];
                for(var i=0; i<this.Records.length; i++){
                    if(this.Records[i].IsSelected && this.Records[i].RowStatus != PublicEnum.RowStatus.Delete){
                        selectRecords.push(this.Records[i]);
                    }
                }
                return selectRecords;
            },
            getRecordIndex: function(record){
                return this.Records.indexOf(record);
            },
            findRecords: function (condition) {
                var results = new Array();

                for (var i = 0; i < this.Records.length; i++) {
                    if(this.Records[i].RowStatus != PublicEnum.RowStatus.Delete) {
                        var isMatch = true;

                        if(condition != undefined && condition != null) {
                            for (var name in condition) {
                                if (eval("this.Records[i]." + name) != condition[name]) {
                                    isMatch = false;
                                    break;
                                }
                            }

                            if (isMatch) {
                                results.push(this.Records[i]);
                            }
                        }
                    }
                }

                return results;
            },
            findRecordById: function(id){
                for (var i = 0; i < this.Records.length; i++) {
                    if(this.Records[i]._id == id){
                        return this.Records[i];
                    }
                }

                return null;
            },
            sort: function(orderBy, completeFun){
                if(orderBy == undefined || orderBy == null){
                    orderBy = this.QueryParameter.OrderBy;
                }

                this.Records.sort(function (a, b) {
                    for (var name in orderBy) {
                        if(orderBy[name] > 0){
                            if (eval("a." + name) > eval("b." + name)) {
                                return 1;
                            }
                            else if (eval("a." + name) < eval("b." + name)) {
                                return -1;
                            }
                        }
                        else{
                            if (eval("a." + name) > eval("b." + name)) {
                                return -1;
                            }
                            else if (eval("a." + name) < eval("b." + name)) {
                                return 1;
                            }
                        }
                    }
                    return 1;
                });

                this.firstPage(completeFun);
            },

            //刷新DataGrid
            refreshDataGrid: function(records){
                if(records == undefined){
                    records = this.Records;
                }
                this._scope.$broadcast(this._ID, records);
            },
            refreshDataGridRows: function(records){
                if(records == undefined)
                {
                    records = [this.FocusedRecord];
                }
                this._scope.$broadcast("RefreshRows" + this._ID, records);
            },
            refreshDataGridDeleteRows: function(records){
                if(records == undefined)
                {
                    records = [this.FocusedRecord];
                }
                this._scope.$broadcast("RefreshDeleteRows" + this._ID, records);
            },

            //翻页方法
            firstPage: function(completeFun){
                this.aassignPage(0, completeFun);
            },
            prePage: function(completeFun){
                if(this.PageNum > 0){
                    this.aassignPage(this.PageNum - 1, completeFun);
                }
            },
            nextPage: function(completeFun){
                if(this.PageNum < this.PageCount - 1){
                    this.aassignPage(this.PageNum + 1, completeFun);
                }
            },
            lastPage: function(completeFun){
                if(this.PageCount > 0) {
                    this.aassignPage(this.PageCount - 1, completeFun);
                }
            },
            aassignPage: function(pageIndex, completeFun){
                if(this.PageCount > 0){
                    pageIndex = parseInt(pageIndex);
                    if(pageIndex > this.PageCount - 1){
                        pageIndex = this.PageCount - 1;
                    }
                    else if(pageIndex < 0) {
                        pageIndex = 0;
                    }

                    var self = this;
                    if (this.LoadMode == PublicEnum.LoadMode.CacheAndNoPaging ||
                        this.LoadMode == PublicEnum.LoadMode.CacheAndDelay) {
                        this.PageNum = pageIndex;
                        var records = this.Records.slice(pageIndex * this.PageSize, (pageIndex+1) * this.PageSize);
                        this.FocusedRecord = records[0];
                        this.refreshDataGrid(records);
                        if(completeFun != undefined && completeFun != null) {
                            completeFun(records);
                        }
                    }
                    else if(this.LoadMode == PublicEnum.LoadMode.CacheAndPaging){
                        if(this.Pages.RecordPages[pageIndex] != undefined){
                            this.PageNum = pageIndex;
                            this.FocusedRecord = self.Pages.RecordPages[pageIndex][0]; 
                            this.refreshDataGrid(self.Pages.RecordPages[pageIndex]);
                            if(completeFun != undefined && completeFun != null) {
                                completeFun(this.Pages.RecordPages[pageIndex]);
                            }
                        }
                        else{
                            var self = this;
                            this.loadByPage(null, null, pageIndex, function(records){
                                self.PageNum = pageIndex;
                                self.Pages.RecordPages[pageIndex] = records;
                                self.FocusedRecord = records[0];  
                                self.refreshDataGrid(records);
                                if(completeFun != undefined && completeFun != null) {
                                    completeFun(records);
                                }
                            });
                        }
                    }
                    else if (this.LoadMode == PublicEnum.LoadMode.NoCacheAndPaging) {
                        this.Records = [];
                        this.loadByPage(null, null, pageIndex, function(records){
                            self.PageNum = pageIndex;
                            self.Records = records;
                            self.FocusedRecord = records[0]; 
                            self.refreshDataGrid(records);
                            if(completeFun != undefined && completeFun != null) {
                                completeFun(records);
                            };
                        });
                    }
                }
                else{
                    this.refreshDataGrid();
                }
            },
            getFocusedPageRecords: function(completeFun){
                this.aassignPage(this.PageNum, completeFun);
            },
            //模拟创建主子关系，暂时只提供关联载入
            createRelation : function(parentModule, scope){
                parentModule.ChildModules.push(this);
                this.ParentModule = parentModule;

                scope.$watch('Module.' + parentModule.EntityName + '.FocusedRecord._id',
                    function (newValue, oldValue, scope) {
                        if (newValue != oldValue) {
                            //加载子Module数据
                            for (var i = 0; i < parentModule.ChildModules.length; i++) {
                                parentModule.ChildModules[i].Records = new Array();

                                if (parentModule.FocusedRecord != null && parentModule.FocusedRecord.RowStatus != PublicEnum.RowStatus.Insert) {
                                    var parentModuleEntityName = parentModule.EntityName;
                                    parentModule.ChildModules[i].load();
                                }
                                else{
                                    parentModule.ChildModules[i].clearRecords();
                                }
                            }
                        }
                    },
                    false
                );
            }
        };

        return {
            //scope: 必输项，作用域
            //entityName： 必输项，文档名称
            initModule: function (scope, moduleName, queryParameter, entityName) {
                if(entityName == undefined){
                    entityName = moduleName;
                }
                var newModule = new publicModule(scope, entityName, queryParameter);

                if(scope.Module == undefined || scope.Module == null){
                    scope.Module = {
                        save: function(successFun) {
                            var saveDatas = new Array();
                            for (var module in this) {
                                if(this[module].Records.length > 0){
                                    var saveRecords = [];
                                    for(var i=0; i<this[module].Records.length; i++){
                                        if(this[module].Records[i].RowStatus != PublicEnum.RowStatus.UnChange){
                                            saveRecords.push(this[module].Records[i]);
                                        }
                                    }
                                    saveRecords = saveRecords.concat(this[module]._DeleteRecords);
                                    var moduleData = {
                                        EntityName: module,
                                        Records: saveRecords
                                    };
                                    saveDatas.push(moduleData);
                                }
                            }

                            if(saveDatas.length > 0){
                                PublicService.saves(saveDatas, function (res) {
                                    if(successFun != undefined){
                                        successFun();
                                    }
                                });
                            }
                        }
                    };
                }

                eval('scope.Module.' + moduleName + ' = newModule');
                newModule._ID = moduleName + new Date().getTime().toString();

                scope.$watch('Module.' + moduleName + '.FocusedRecord',
                    function (newValue, oldValue, scope) {
                        if (newValue != null && oldValue != null && newValue._id == oldValue._id 
                            && newValue.RowStatus == oldValue.RowStatus && newValue.IsSelected == oldValue.IsSelected) {
                            if (newValue.RowStatus == PublicEnum.RowStatus.UnChange) {
                                eval('scope.Module.' + moduleName + '.FocusedRecord.RowStatus = PublicEnum.RowStatus.Modify');
                            }
                        }
                    },
                    true
                );

                return newModule;
            }
        }
    }
]);
